#!/bin/bash

load inquirer

required() {
  if [ "$1" = "" ]; then
    echo false
  else
    echo true
  fi
}

create() {
  local service_name=$1
  local service_command=${@:2}
  local is_daemon_force_recreate=false

  # while [[ $# -gt 0 ]]; do
  #   local key=$1
  #   local value=$2
  #   case $key in
  #     -f | --force-recreate)
  #       os::set_var is_daemon_force_recreate true
  #       shift
  #       ;;
  #     *)
  #       if [ "$(string::match $key ^-)" = "true" ]; then
  #         echo "[daemon][create]: unknown parameter \"$key\""
  #         help
  #         exit 1
  #       fi

  #       service_name=$key
  #       shift
  #       ;;
  #   esac
  # done

  if [ -z "$service_name" ]; then
    inquirer::text "daemon service name:" service_name "" "service name is required" required
  fi

  if [ -z "$service_command" ]; then
    inquirer::text "daemon service command:" service_command "" "service command is required" required
  fi

  log::info ""
  log::info "create service ..."
  log::info "#################################"
  log::info "service_name: $service_name"
  log::info "service_command: $service_command"
  log::info "#################################"

  local yesno=('Yes' 'No')
  inquirer::select "is it ok ?" yesno answer
  if [ "$answer" != "Yes" ]; then
    exit 0
  fi

  if [ "$is_daemon_force_recreate" = "false" ]; then
    if [ "$(daemon_has_service $service_name)" = "true" ]; then
      local yesno=('Yes' 'No')
      inquirer::select "override ?" yesno answer
      if [ "$answer" != "Yes" ]; then
        exit 0
      fi

      is_daemon_force_recreate=true
    fi
  fi

  if [ "$is_daemon_force_recreate" = "true" ]; then
    daemon_remove $service_name
  fi

  daemon_create $service_name $service_command
}

help() {
  echo "Create a daemon service"
  echo ""
  echo "Usage:"
  echo "  zdaemon create [options] [name] [commands...]"
  echo ""
  echo "Options:"
  echo "  -f, --force-recreate  Force recreate service"
}

core() {
  if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    help
    exit 0
  fi

  create $@
}

run() {
  core $@
}

run $@
